import SearchTop from "../../components/newSearchTop.vue";
import SearchTitle from "../../components/newSearchTitle.vue";
import getAwardDetail from '@/api/award/award-add';
import axios from 'axios';
import reportEvent from "../../components/report.js"
import $store from "../../components/vuex.js"
import Footer from "../../components/footer.vue"

export default {
    components: {
        SearchTop: SearchTop,
        SearchTitle: SearchTitle,
        Footer: Footer,
    },

    data() {
        return {
            userName: "",
            //gameId: this.$route.query.gameId,
            gameId: this.$route.query.gameId,
            //获取用户信息
            imgUrl: "",
            token: window.sessionStorage.getItem("token"),
            userId: '',
            //YY签名以及时间戳
            signs: '',
            timestamp: '',
            //获取YY游戏标识即game值
            softid: '',
            tabs: ['双线服', '新服'],
            num: 0,
            list: '双线服,',
            //下拉加载
            fst: false,
            loading: false,
            loadingText: '加载中...',
            //分页参数
            gsPageNo: 1,
            latest: {
                servers: []
            },
            result: [],
            allServices: {
                servers: []
            },
            playLatests: [],
            //进入游戏
            ifEnter: '',
            inputText: '',
            lenovoId:window.sessionStorage.getItem("lenovoId"),
            //进入游戏接口
            gameurl: "http://pitf.vgs.lenovo.com.cn",
            gameName:'',
            //区服号
            serverNumber: [],
            startTime: +new Date(),
            gameData:{},
            //未获取到数据时加载文字
            softBrowser: 'chrome', //浏览器类型
        }
    },

    mounted() {

        this.userName = window.sessionStorage.getItem("userName")

        console.log(this.userName)

        //获取YY游戏标识game值

        this.getGame(this.gameId);
        //获取YY签名以及时间戳

        this.winSrcoll()
        if (typeof this.$route.query.errorMessage != "undefined" && this.$route.query.errorMessage != "") {
            this.$toast.center("错误")
        };

        this.getGameDetails()
        this.getUserInfo()
        reportEvent.pageIn(this.userId, '109')

    },
    beforeDestroy() {
        reportEvent.pageOut(this.userId, this.startTime, "109")

    },

    created() {
        //防止页面后退
        //处理键盘事件 禁止后退键（Backspace）密码或单行、多行文本框除外 
        function banBackSpace(e) {
            var ev = e || window.event; //获取event对象 
            var obj = ev.target || ev.srcElement; //获取事件源 

            var t = obj.type || obj.getAttribute('type'); //获取事件源类型 

            //获取作为判断条件的事件类型 
            var vReadOnly = obj.getAttribute('readonly');
            var vEnabled = obj.getAttribute('enabled');
            //处理null值情况 
            vReadOnly = (vReadOnly == null) ? false : vReadOnly;
            vEnabled = (vEnabled == null) ? true : vEnabled;

            //当敲Backspace键时，事件源类型为密码或单行、多行文本的， 
            //并且readonly属性为true或enabled属性为false的，则退格键失效 
            var flag1 = (ev.keyCode == 8 && (t == "password" || t == "text" || t == "textarea") &&
                (vReadOnly == true || vEnabled != true)) ? true : false;

            //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效 
            var flag2 = (ev.keyCode == 8 && t != "password" && t != "text" && t != "textarea") ?
                true : false;

            //判断 
            if (flag2) {
                return false;
            }
            if (flag1) {
                return false;
            }
        }

        //禁止后退键 作用于Firefox、Opera 
        document.onkeypress = banBackSpace;
        //禁止后退键 作用于IE、Chrome 
        document.onkeydown = banBackSpace;
    },

    methods: {
        //
        scrollTop(){
            $(".scrollData").scrollTop(0)

        },

        getUserInfo() { // 通过token来获取用户的基本信息
            var ts = this
            let url = "/token/user/getUserInfo?time=" + new Date().getTime(); // 防止缓存
            this.jqajax(url, { type: "POST", dataType: "json", data: { token: ts.token } }, function(res) {
                console.log(res)
                ts.user = res.data
                ts.userName = res.data.nickname
                console.log(ts.user)
                ts.userId = ts.user.lenovoId
                ts.getSign(ts.user.lenovoId)
            })
        },

        //获取游戏详情 
        getGameDetails() {
            let that = this
            console.log(this.gameId)
            var url = "/back/game/get/game/detail/name?relativeId=48&gameId=" + this.gameId
            
            axios.get(url).then(function(res) {
                for (var i = 0; i < res.data.data.captureFiles.length; i++) {
                    if (res.data.data.captureFiles[i].size == "270*600") {
                        that.imgUrl = res.data.data.captureFiles[i].url;
                    }
                }

            })
        },

        //获取YYgame
        getGame(gameId, callback) {
            var _url = "/back/game/get/game/soft/data?softName=yy" + "&gameId=" + gameId;
            var ts = this;
            ts.jqajax(_url, { type: "get", dataType: "json" }, function(res) {
                console.log('game', res);

                ts.gameData = res.data
                console.log( ts.gameData)

                ts.softBrowser = res.data.softkernel;
                ts.softid = res.data.softId; //game值

              ts.getAllServer(ts.softid, ts.gsPageNo); //获取所有区服
                ts.getNewInfo(ts.softid)

                 //ts.getLastServer(res.data.softName,res.data.softId,ts.lenovoId)

            });
        },

        winSrcoll() {
            var ts = this;
            $(".changeSev").scroll(function() {
                
                //节流事件
                if (ts.fst) {

                    var scrollTop = $(this).scrollTop() //滑动的距离
                    var scrollHeight = $(".scrollData").height() //文本的高度
                    var windowHeight = $(this).height() //可视窗口的高度

                    if (scrollHeight - windowHeight - scrollTop <= 10 && !ts.loading) {
                        ts.getSecond(ts.softid, ts.gsPageNo);
                    }
                }


            });
        },

        getSecond(game, gsPageNo) {
            var ts = this;
            var gsPageNo = gsPageNo ? gsPageNo : "1";
            ts.loading = true;
            var url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&order=opentime:desc&serverType=GENERAL&gsPageSize=60&online" + "&game=" + game + "&gsPageNo=" + gsPageNo;
            console.log(url)
            this.jqajax(url, { type: "post", dataType: "jsonp" }, (res) => {
                console.log(res)
                ts.loading = false;
                var _servers = res[game].servers;
                console.log(_servers)
                if (JSON.stringify(_servers) == "{}") {
                    ts.loadingText = '已无更多区服';
                    ts.fst = false;
                    return false;
                } else {
                    for (var item in _servers) {
                        ts.result.push(_servers[item]);
                    }
                    // console.log('第二个servers', ts.allServices.servers)
                    ts.allServices.servers = ts.allServices.servers.concat(ts.result);
                    ts.result.length = 0;
                }
            });
            ts.gsPageNo++;
        },

        //检测客户端
        isLenovo() {
            var usr = navigator.userAgent;
            if (usr.toLowerCase().indexOf("lenovocenter") > -1) {
                return true;
            }
            return false;
        },

        getAllServer(game, gsPageNo) { // 参数为游戏的softid
            $(window).scrollTop(0);
            var ts = this;
            var gsPageNo = gsPageNo ? gsPageNo : "1";
            ts.loading = true;
            var url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&serverType=GENERAL&order=opentime:desc&gsPageSize=60&online" + "&game=" + game + "&gsPageNo=" + gsPageNo;
            this.jqajax(url, {}, (res) => {
                ts.fst = true;
                ts.loading = false;
                var _servers = res[ts.softid].servers;
                console.log('所有', _servers, ts.softid);
                for (var item in _servers) {
                    ts.allServices.servers.push(_servers[item]);
                }
                
                console.log('循环之后的结果数组', ts.allServices.servers)
                console.log('长度', ts.allServices.servers.length)
                ts.gsPageNo++;
            });

        },

        getNewInfo(game) {
            var ts = this;
            var url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&serverType=GENERAL&order=opentime:desc&gsPageNo=1&gsPageSize=20&online" + "&game=" + game;
            ts.jqajax(url, {}, (res) => {
                console.log('最新区服信息', res);

                var _servers = res[ts.softid].servers;
                for (var item in _servers) {
                    ts.latest.servers.push(_servers[item]);
                }
                ts.latest.servers = ts.latest.servers.slice(0, 5);

                console.log('最新区服信息输出', ts.latest.servers)
            })
        },

        //获取yy签名以及当前时间戳
        getSign(userId) {
            var _url = "/back/game/api/user/md5UserId?userId=" + userId + "&time=" + new Date().getTime();
            var ts = this;
            ts.jqajax(_url, { type: "get", dataType: "json" }, function(res) {
                ts.signs = res.data.out;
                ts.timestamp = res.data.timestamp;
                //获得以前玩的游戏
                ts.playLatest(ts.softid, ts.signs, ts.timestamp, ts.userId);
            });
        },
        //进入游戏
        enterGame() {
            //获取用户输入的区服号
            var words = this.$refs.inputData.value;
            //console.log(words);
            if (words && words != "") {
                if (/^\+?[1-9][0-9]*$/.test(words)) {
                    this.inputText = 's' + this.$refs.inputData.value;

                    this.gameStart(this.softid,this.gameName,this.inputText);
                } else {
                    this.$toast.top('请输入数字格式的区服号');
                }
            } else {
                this.$toast.top('请输入数字格式的区服号');
            }

        },
        //获取用户最近在玩的
        playLatest(game, sign, timestamp, userId) {
            var ts = this;
            // &serverType=GENERAL
            var url = this.gmConf.domainHttps + "unionlogin.4366.com/lenovo/gamecenter/recently.do?jsonp&order=opentime:desc" + "&game=" + game + "&sign=" + sign + "&timestamp=" + timestamp + "&userId=" + userId + "&time=" + new Date().getTime()
            this.jqajax(url, {}, (res) => {
                console.log(res.data)
                $(".service-specific-container div").eq(0).remove();
                if (res.data.length > 4) {
                    ts.playLatests = res.data.slice(0, 3);
                } else {
                    ts.playLatests = res.data.slice(0, 3);
                }
                 ts.gameName = ts.playLatests[0].gameName

            })
        },

        //客户端弹窗
        popVideo(_url) {
            var ts = this;
            if (!_url || !ts.isLenovo()) return;
            if (!ts.isIe()) {
                callHostFunction.callBackVideo(_url, ts.softBrowser);
            } else {
                window.external.callBackVideo(_url, ts.softBrowser);
            }

        },

        getLastServer(cpId,softId,lenovoId){// 获取用户最近玩的区服

            let url = `/token/transfer/getUserAreaGamesList?cp=${cpId}_GAME&game=${softId}&lenovoId=${lenovoId}`
            let that=this;
            axios.get(url).then(function(res){
                if(res.data.code==0 || JSON.stringify(res.data.giftBags)!='[]'){
                    that.hotGiftList = res.data.giftBags;

                    that.hotGiftList = that.hotGiftList[0];
                }else{
                    $toast.center("请求错误")
                }

            },function(err){

            })
        },


        //开始游戏
        gameStart(cpId,gameName,softId,serverId,serviceName) {//  cpId 游戏名称  softId   gameId  区服id，区服名
                let that = this;
                var url = `${this.gameurl}/gameRedirect/loginGame?cp=${cpId}_GAME&game=${softId}&gameName=${gameName}&token=${this.token}`
                this.saveGame(window.sessionStorage.getItem("lenovoId"),cpId,softId,48,serverId,serviceName,gameName)
                window.open(url)
                reportEvent.pageStartGame(this.userId)
        },
        saveGame(lenovoId,cpId,softId, relativeId, serverId,serviceName,gameName) { // 记录玩过的游戏 联想ID cpId softId  平台编号 区服id 区服名 游戏名
            let that = this;
            if (serverId && serviceName) {
                this.resSaveGame(lenovoId,cpId,softId, relativeId,serverId ,serviceName,gameName)
            } else {
                console.log(softId)
                let _url = this.gmConf.domainHttps+"unionlogin.4366.com/lenovo/gamecenter/gslist.do?jsonp&serverType=GENERAL&order=opentime:dasc&gsPageSize=5&online" + "&game=" + softId +"&gsPageNo=1"
                console.log(_url)
                that.jqajax(_url, { type: "post", dataType: "jsonp" },function(res){

                    var _servers = res[softId].servers;
                    var arr = []
                    for (var item in _servers) {
                        arr.push(_servers[item]);
                    }
                    that.newService = arr[0]
                    console.log(that.newService)

                    that.resSaveGame(lenovoId,cpId,softId, relativeId, that.newService.id,that.newService.name,gameName)

                });
            }

        },
        resSaveGame(lenovoId,cpId,softId,relativeId,serverId,serviceName,gameName){
            let that =this
             let url = `/gift/api/webpagegame/collectionGame.do?lenovoId=${lenovoId}&relativeId=${relativeId}&serverId=${serverId}&softId=${softId}&serverName=${serviceName}&gameName=${gameName}&softName=${cpId}`;
                axios.get(url).then(function(res) {
                    if (res.data.code == 0) {
                    } else {
                        that.$toast.center("请求错误")
                    }

                }, function(err) {

                })

        },


    }

}